<template>
    <div class="new-sales-order" style="width: 1200px">
      <h3>新增销售订单 <span style="color: red">*</span>为必填项</h3>
      <br />
      <el-form :model="form" label-width="80px">
        <div class="form-row">
          <el-form-item label="销售单号:">
            <el-input
              disabled
              v-model="form.sellStringCode"
              placeholder="可不填写，自动生成"
            ></el-input>
          </el-form-item>
          <el-form-item label="* 单据类型">
            <el-select v-model="form.sellType" placeholder="请选择入库类别">
              <el-option label="等待入库" value="等待入库"></el-option>
              <el-option label="批准入库" value="批准入库"></el-option>
            </el-select>
          </el-form-item>
          <el-form-item label="关联订单号">
            <el-input v-model="form.productNum"></el-input>
          </el-form-item>
        </div>
        <div class="form-row">
          <el-form-item label="客户编号">
            <el-input disabled v-model="form.customerNum"></el-input>
          </el-form-item>
          <el-form-item label="客户名称">
            <el-input v-model="form.customerName"></el-input>
          </el-form-item>
          <el-form-item label="联系人">
            <el-input v-model="form.contactsName"> </el-input>
          </el-form-item>
        </div>
        <div class="form-row">
          <el-form-item label="电话">
            <el-input v-model="form.phone"></el-input>
          </el-form-item>
          <el-form-item label="发货日期">
            <el-input v-model="form.startTime" type="date"></el-input>
          </el-form-item>
          <el-form-item label="备注">
            <el-input v-model="form.sellDesc" type="textarea"></el-input>
          </el-form-item>
        </div>
        <div class="form-row">
          <el-form-item label="制单人">
            <el-input v-model="form.preparedBy" disabled></el-input>
          </el-form-item>
          <el-form-item label="制单时间">
            <el-input v-model="form.preparedTime" disabled></el-input>
          </el-form-item>
        </div>
      </el-form>
      <div class="product-info">
        <h4>产品信息</h4>
        <div style="text-align: right; margin-bottom: 10px">
          <el-button
            type="primary"
            icon="el-icon-plus"
            size="small"
            @click="openProductSelector"
            class="action-button"
            >新增产品</el-button
          >
        </div>
        <el-table :data="productList" border style="width: 1200px">
          <el-table-column type="selection" width="55"></el-table-column>
          <el-table-column label="产品名称" prop="productName"></el-table-column>
          <el-table-column label="产品编码" prop="productNum"></el-table-column>
          <el-table-column label="规格" prop="specification"></el-table-column>
          <el-table-column label="单位" prop="unitName"></el-table-column>
          <el-table-column label="单价" prop="price"></el-table-column>
          <el-table-column label="数量">
            <template #default="scope">
              <el-input
                v-model="scope.row.quantity"
                placeholder="输入数量"
                class="table-input"
                @input="calculateTotal(scope.row)"
              ></el-input>
            </template>
          </el-table-column>
          <el-table-column label="总价" prop="totalPrice"></el-table-column>
          <el-table-column label="操作" width="180">
            <template #default="scope">
              <el-button icon="el-icon-delete" @click="deleteProduct(scope.row)"
                >删除</el-button
              >
            </template>
          </el-table-column>
        </el-table>
      </div>
      <div style="text-align: center; margin-top: 20px">
        <el-button type="primary" @click="submitForm()">提交</el-button>
        <el-button style="margin-left: 10px" @click="cancelForm">取消</el-button>
      </div>
    </div>
    <el-dialog
      title="选择产品"
      ref="dialogRef"
      v-model="dialogVisible"
      width="1200px"
    >
      <el-form :model="searchParams" class="search-form">
        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="产品编号">
              <el-input
                v-model="searchParams.productId"
                placeholder="请输入编码"
                class="form-input"
              />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="产品名称">
              <el-input
                v-model="searchParams.productName"
                placeholder="请输入名称"
                class="form-input"
              />
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
      <div class="search-button-container">
        <el-button type="primary" @click="searchProducts" class="search-button">
          搜索
        </el-button>
      </div>
      <br />
      <el-table
        @selection-change="handleSelectionChange"
        :data="dialogProductList"
        border
        class="product-table"
      >
        <el-table-column type="selection"></el-table-column>
        <el-table-column label="产品编码" prop="productNum"></el-table-column>
        <el-table-column label="产品名称" prop="productName"></el-table-column>
        <el-table-column label="规格" prop="specification"></el-table-column>
        <el-table-column label="存储单位" prop="unitName"></el-table-column>
        <el-table-column label="单价" prop="price"></el-table-column>
      </el-table>
      <br />
      <el-pagination
        v-model:current-page="form1.PageIndex"
        v-model:page-size="form1.PageSize"
        :page-sizes="[1, 3, 15, 100]"
        :size="size"
        :disabled="disabled"
        :background="background"
        layout="total, sizes, prev, pager, next, jumper"
        :total="form1.TotalCount"
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
      />
      <br />
      <div class="button-group">
        <el-button @click="closeDialog" class="action-button"> 关闭 </el-button>
        <el-button type="primary" @click="confirmSelection" class="action-button">
          选择
        </el-button>
      </div>
    </el-dialog>
  </template>
  
  <script setup lang="ts">
  import { ElMessageBox, ElMessage, type FormInstance } from "element-plus";
  import { reactive, onMounted, ref } from "vue";
  import axios from "axios";
  import { useRouter, useRoute } from "vue-router";
  import dayjs from "dayjs";
import { KongaUrl } from "@/axios/axiosHelp";
  const router = useRouter();
  const route = useRoute();
  
  //分页
  const form1 = reactive({
    TotalCount: 0,
    PageCount: 0,
    PageSize: 5,
    PageIndex: 1,
  });
  const handleSizeChange = (newSize) => {
    form1.PageSize = newSize;
    searchProducts();
  };
  const handleCurrentChange = (newPage) => {
    form1.PageIndex = newPage;
    searchProducts();
  };
  //获取产品信息
  const openProductSelector = () => {
    dialogVisible.value = true;
    searchProducts();
  };
  const productList = ref([]);
  const dialogProductList = ref([]);
  
  const dialogVisible = ref(false);
  const searchParams = ref({
    productCode: "",
    productName: "",
  });
  const searchProducts = () => {
    KongaUrl
      .get("/wangcong/api/Whouase/GetPtodtos", {
        params: {
          PageSize: form1.PageSize,
          PageIndex: form1.PageIndex,
        },
      })
      .then((res) => {
        dialogProductList.value = res.data.data.list;
        form1.TotalCount = res.data.data.totalCount;
        form1.PageCount = res.data.data.PageCount;
      })
      .catch((error) => {
        console.error("获取产品列表失败", error);
      });
  };
  
  const deleteProduct = (product) => {
    ElMessageBox.confirm("确定要删除该产品吗？", "提示", {
      confirmButtonText: "确定",
      cancelButtonText: "取消",
      type: "warning",
    })
      .then(() => {
        const index = productList.value.indexOf(product);
        if (index !== -1) {
          productList.value.splice(index, 1);
        }
      })
      .catch(() => {});
  };
  
  const dialogSelection = ref<any[]>([]);
  const handleSelectionChange = (val: any[]) => {
    dialogSelection.value = val;
  };
  
  const confirmSelection = () => {
    const selectedRows = dialogSelection.value;
    if (selectedRows.length === 0) {
      ElMessage.warning("请选择产品");
      return;
    }
    selectedRows.forEach((selectedProduct) => {
      productList.value.push({
        productName: selectedProduct.productName,
        productNum: selectedProduct.productNum,
        productId: selectedProduct.productId,
        specification: selectedProduct.specification,
        unitName: selectedProduct.unitName,
        price: selectedProduct.price,
        quantity: "",
        totalPrice: "",
      });
    });
    closeDialog();
  };
  
  const closeDialog = () => {
    dialogVisible.value = false;
    searchParams.value.productCode = "";
    searchParams.value.productName = "";
    dialogProductList.value.forEach((row) => {
      row._checked = false;
    });
  };
  const form = ref({
    sellStringCode: "",
    sellType: "",
    productNum: (route.query.productNum as string) || "",
    customerNum: "",
    customerName: "",
    contactsName: "",
    phone: "",
    startTime: dayjs().format("YYYY-MM-DD"),
    sellDesc: "",
    preparedBy: "陈平安",
    preparedTime: dayjs().format("YYYY-MM-DD"),
    stute: false,
  });
  //计算总价
  const calculateTotal = (row: any) => {
    if (row.quantity !== "" && row.price !== "") {
      row.totalPrice = (Number(row.quantity) * Number(row.price)).toFixed(2);
    } else {
      row.totalPrice = "";
    }
  };
  const ruleFormRef = ref<FormInstance>();
  // 提交表单方法
  const submitForm = async () => {
    if (!form.value.sellType) {
      ElMessage.error("请选择单据类型");
      return;
    }
  
    const payload = {
      ...form.value,
      ProductNewSellModelId: productList.value[0]?.productNewSellModelId || 0, // 主表ID
      products: productList.value.map((item) => ({
        productId: item.productId,
        quantity: Number(item.quantity),
        price: Number(item.price),
        totalPrice: Number(item.totalPrice),
        productNum: item.productNum,
        productName: item.productName,
        specification: item.specification,
        unitId: item.unitId,
      })),
    };
  
    try {
      const res = await KongaUrl.post(
        "/wangcong/api/WHouase/UpdateSell",
        payload
      );
      if (res.data.code === 300) {
        ElMessage.success("修改成功");
        router.push("/GetSell");
      } else {
        ElMessage.error(res.data.message);
      }
    } catch (error) {
      ElMessage.error("请求失败，请检查控制台");
      console.error("API Error:", error);
    }
  };
  const generateTwelveDigitNumber = () => {
    const characters = "0123456789";
    let result = "";
    for (let i = 0; i < 12; i++) {
      // 生成12位数字
      result += characters.charAt(Math.floor(Math.random() * characters.length));
    }
    return result;
  };
  const cancelForm = () => {
    console.log("取消表单");
  };
  onMounted(() => {
    handleView(); // 组件加载时自动执行反填
  });
  //反填
  //#region  反填入库订单号的基本信息和产品信息
  //订单基本信息表单
  const UpdateinboundInventoryform = reactive({
    sellStringCode: "",
    sellType: "",
    productNum: (route.query.productNum as string) || "",
    customerNum: "",
    customerName: "",
    contactsName: "",
    phone: "",
    startTime: dayjs().format("YYYY-MM-DD"),
    sellDesc: "",
    preparedBy: "陈平安",
    preparedTime: dayjs().format("YYYY-MM-DD"),
    stute: false,
  });
  
  // 产品类型定义
  interface ProductItem {
    ProductNewSellModelId?: number | null; // 关联表ID（新增）
    quantity: string;
    price: string;
    totalPrice: string;
    productNum: string;
    productName: number | string;
    specification: number | string;
    unitId: string;
  }
  // 查看方法 - 修改为自动执行
  const handleView = () => {
    const sellStringCode = route.query.productNum; // 改为通过销售单号查询
  
    if (!sellStringCode) {
      console.log("未获取到销售单号");
      return;
    }
  
    // 统一使用form.value来管理表单数据
    form.value.productNum = sellStringCode as string;
  
    // 获取入库单基本信息
    KongaUrl
      .get(`/wangcong/api/Whouase/GetNewSellModels`, {
        params: {
          ProductNum: sellStringCode, // 确保后端API接收这个参数
        },
      })
      .then((res) => {
        if (res.data.data && res.data.data.length > 0) {
          const basicInfo = res.data.data[0];
          Object.assign(form.value, {
            ...basicInfo,
            // 确保日期格式匹配el-input的type="date"
            startTime: dayjs(basicInfo.startTime).format("YYYY-MM-DD"),
            preparedTime: dayjs(basicInfo.preparedTime).format("YYYY-MM-DD"),
          });
        }
      });
  
    // 获取产品信息
    KongaUrl
      .get(`/wangcong/api/Whouase/GetnewProducts`, {
        params: {
          ProductNum: sellStringCode, // 确保后端API改为通过销售单号查询
        },
      })
      .then((res) => {
        productList.value = res.data.data.map((item) => ({
          ProductNewSellModelId: item.productNewSellModelId,
          productId: item.productId,
          quantity: item.quantity,
          price: item.price,
          totalPrice: item.totalPrice,
          productNum: (route.query.productNum as string) || "",
          productName: item.productName,
          specification: item.specification,
          unitId: item.unitId,
          unitName: item.unitName,
        }));
      });
  };
  </script>
  
  <style scoped>
  .new-sales-order {
    padding: 20px;
  }
  
  .form-row {
    display: flex;
    margin-bottom: 15px;
  }
  
  .form-row .el-form-item {
    flex: 1;
    margin-right: 20px;
  }
  
  .form-row .el-form-item:last-child {
    margin-right: 0;
  }
  
  .product-info {
    margin-top: 20px;
  }
  </style>